package com.boot.security.server.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class KaptchaValidateCodeFilter extends AbstractAuthenticationProcessingFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;

    public KaptchaValidateCodeFilter(String servletPath, String failureUrl) {
        super(servletPath);
        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String rightCode = (String) req.getSession().getAttribute("vrifyCode");
        String tryCode = req.getParameter("tryCode");
        if (StringUtils.equals("/login", req.getRequestURI())
                && StringUtils.equalsIgnoreCase(req.getMethod(), "post")) {
            // 1. 进行验证码的校验
            if (!rightCode.equalsIgnoreCase(tryCode)) {
                unsuccessfulAuthentication(req, res, new InsufficientAuthenticationException("输入的验证码不正确"));
            }
        }
        // 2. 校验通过，就放行
        filterChain.doFilter(request, response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        return null;
    }

}
